﻿using System;
using System.Data;
using System.Data.SQLite;

namespace MyLib.ViewStateServer {
	/// <summary>
	/// 
	/// </summary>
	internal static class DataAdapter {
		private static IDbConnection m_connection;

		/// <summary>
		/// 
		/// </summary>
		public static void Initialize() {
			System.Diagnostics.Debug.Assert(m_connection == null);

			m_connection = new SQLiteConnection("Data Source=:memory:");
			m_connection.Open();

			var cmd = m_connection.CreateCommand();
			cmd.CommandText =
@"CREATE TABLE BAG (
TIME_POINT INTEGER NOT NULL,
CONTENT BLOB NOT NULL
)";
			cmd.ExecuteNonQuery();
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static byte[] FindById(long id) {
			var cmd = m_connection.CreateCommand();
			cmd.CommandText =
@"SELECT CONTENT FROM BAG 
WHERE ROWID = @ROWID";

			var paramRowId = cmd.CreateParameter();
			paramRowId.ParameterName = "ROWID";
			paramRowId.DbType = DbType.Int64;
			paramRowId.Value = id;
			cmd.Parameters.Add(paramRowId);

			return cmd.ExecuteScalar() as byte[];
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="timepoint"></param>
		/// <param name="content"></param>
		/// <returns></returns>
		public static long Insert(DateTime timepoint, byte[] content) {
			var cmd = m_connection.CreateCommand();
			cmd.CommandText =
@"INSERT INTO BAG (TIME_POINT, CONTENT)
VALUES(@TIME_POINT, @CONTENT)";

			var paramTimepoint = cmd.CreateParameter();
			paramTimepoint.ParameterName = "TIME_POINT";
			paramTimepoint.DbType = DbType.Int64;
			paramTimepoint.Value = timepoint.ToBinary();
			cmd.Parameters.Add(paramTimepoint);

			var paramContent = cmd.CreateParameter();
			paramContent.ParameterName = "CONTENT";
			paramContent.DbType = DbType.Binary;
			paramContent.Value = content;
			cmd.Parameters.Add(paramContent);

			if (cmd.ExecuteNonQuery() > 0) {
				cmd.CommandText = @"SELECT last_insert_rowid()";
				return Convert.ToInt64(cmd.ExecuteScalar());
			} else {
				return 0;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="timepoint"></param>
		public static void ClearNouse(DateTime timepoint) {
			var cmd = m_connection.CreateCommand();
			cmd.CommandText =
@"DELETE FROM BAG WHERE TIMT_POINT < @TIME_POINT";

			var paramTimepoint = cmd.CreateParameter();
			paramTimepoint.ParameterName = "TIME_POINT";
			paramTimepoint.DbType = DbType.Int64;
			paramTimepoint.Value = timepoint.ToBinary();
			cmd.Parameters.Add(paramTimepoint);

			cmd.ExecuteNonQuery();
		}
	} // end of DataAdapter.
}
